package cn.exrick.manager.controller;

import cn.exrick.common.pojo.DataTablesResult;
import cn.exrick.manager.pojo.TbReport;
import cn.exrick.manager.service.ReportService;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

@RestController
public class ReportController {
    @Autowired
    private ReportService reportService;
    @Value("${FILE_STORE_PATH}")
    private String storePath;

    @RequestMapping("/report/list")
    public DataTablesResult getReportList(){
        List<TbReport> reportList = reportService.getReportList();
        DataTablesResult result = new DataTablesResult();
        result.setData(reportList);
        result.setRecordsTotal(reportList.size());
        result.setRecordsFiltered(reportList.size());
        return result;
    }


    @RequestMapping("/report/download")
    public void downloadReport(String fileName, HttpServletResponse response){
        File file = new File(storePath + File.separator + fileName + ".xls");
        try {
            String fileNameIso = new String(fileName.getBytes(), "ISO8859-1");
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileNameIso+".xls");
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
            OutputStream out = response.getOutputStream();
            FileUtils.copyFile(file,out);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
